package com.macro.mall.tiny.component;

import cn.hutool.core.lang.Chain;
import com.macro.mall.tiny.common.util.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ：czx
 * @date ：Created in 2021/7/15 17:05
 * @descriptioin: JWT授权过滤器
 * @modified By：
 */

public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    private static final Logger LOGGER= LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;


    /**
     * description:
     * @ parm:请求作用域,响应作用域,作文件过滤的对象
     * @ return parm:
     */
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {

        String authHeader=httpServletRequest.getHeader(this.tokenHeader);//获取token的请求头
        if (authHeader!=null && authHeader.startsWith(this.tokenHead)){ //或者这个字符串的前缀

            String authToken=authHeader.substring(this.tokenHead.length());//the part after Bearer--substring() 方法返回字符串的子字符串。
            String username = jwtTokenUtil.getUserNameFromToken(authToken);//那就是Bearer作为参数

            LOGGER.info("【请求参数：】checking username:{}",username);//输入本次的校验数据
            if (null!=username && null== SecurityContextHolder.getContext().getAuthentication()){
                UserDetails userDetails=this.userDetailsService.loadUserByUsername(username);//获取数据库的用户信息
                if (jwtTokenUtil.validateToken(authToken,userDetails)){//进行比对
                    UsernamePasswordAuthenticationToken authentication=new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
                    LOGGER.info("【返回参数是：】authenticated user:{}",username);
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}
























































